import axios from 'axios';
import { RESULTTYPE, NOLOGINSTATUS, CUSTOMHEADER } from '@/utils/consts';
import { recurseData } from './common-utils';
import moment from 'moment';
import _ from 'lodash';

const instance = axios.create({
  withCredentials: true,
  headers: {
    'X-Requested-With': 'XMLHttpRequest'
  }
});
// 默认对日期自动格式化为字符串
instance.interceptors.request.use(config => {
  if (config.method.toLowerCase() !== 'get' && config.handleDate !== false) {
    const handledData = recurseData(config.data, value => {
      if (_.isDate(value)) {
        return moment(value).format('YYYY-MM-DD hh:mm:ss');
      }
      if (_.isString(value)) {
        return _.trim(value);
      }
      return value;
    });
    config.data = handledData;
  }
  return config;
});
// 处理未登录的情况
instance.interceptors.response.use((response) => {
  const headerJson = JSON.parse(response.headers[CUSTOMHEADER.toLocaleLowerCase()] || '{}');
  const loginTimeoutHandler = response.config.loginTimeoutHandler;
  const timeoutHandler = response.config.timeoutHandler;
  if (headerJson.status === NOLOGINSTATUS) {
    const redUrl = headerJson.headers.location;
    if (_.isFunction(timeoutHandler)) {
      timeoutHandler(redUrl, response);
    } else {
      window._vueInstance.$Modal.warning({
        title: '登录过期',
        content: '登录已过期,点击确定重新登录',
        closable: false,
        maskClosable: false,
        onOk: () => {
          if (loginTimeoutHandler) {
            loginTimeoutHandler(redUrl, response);
          } else {
            window.location = redUrl;
          }
        }
      });
    }
  }
  return response;
});

// 根据返回结果和调用时参数进行提醒
instance.interceptors.response.use((response) => {
  const isNotify = response.config.notify;
  const customNotifyMessage = response.config.notifyMessage;
  const result = response.data;
  const $Message = window._vueInstance.$Message;

  let message = result.message;
  if (_.isFunction(customNotifyMessage)) {
    message = customNotifyMessage(result, response);
  }
  if (_.isString(customNotifyMessage) && (RESULTTYPE.NORMAL === result.type || result.type === 'NORMAL')) {
    message = customNotifyMessage;
  }
  if (isNotify) {
    if (RESULTTYPE.NORMAL === result.type || result.type === 'NORMAL') {
      $Message.success(message);
    }
    if (RESULTTYPE.WARRING === result.type || result.type === 'WARRING') {
      $Message.warning(message);
    }
  }
  if (result.type === RESULTTYPE.FAILED || result.type === 'FAILED') {
    $Message.error(message);
  }
  if (result.type === 'INVALID_MODEL') {
    window._vueInstance.$pub('on-invalid-model', result.data);
  }
  return response;
});

// 处理返回结果
instance.interceptors.response.use((response) => {
  return response.data;
}, (error) => {
  window._vueInstance.$Message.error('系统错误，请联系管理员！');
  return Promise.reject(error);
});

export default instance;
